/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/IResourceLoader.hpp"
#include "Xern/DataFilter.hpp"
#include "Xern/DataStream.hpp"
#include "Xern/Exceptions.hpp"
#include "Xern/FileSystem.hpp"
#include "Xern/Engine.hpp"
#include "Xern/PluginFactory.hpp"
#include "Xern/ResourceManager.hpp"
#include "WavSampler.hpp"

namespace XernWav
{
	// Wave header.
	struct WaveHeader
	{
		static const u32 ChunkID = XERN_FOURCC('R', 'I', 'F', 'F');
		static const u32 Format = XERN_FOURCC('W', 'A', 'V', 'E');
		u32 chunkId;
		u32 chunkSize;
		u32 format;
	};

	// Wave format structure.
	struct WaveFormat
	{
		static const u32 ChunkID = XERN_FOURCC('f', 'm', 't', ' ');
		static const u32 ChunkSize = 16;
		static const u16 PcmFormat = 1;

		u32 subchunkId;
		u32 subchunkSize;
		u16 audioFormat;
		u16 numChannels;
		u32 sampleRate;
		u32 byteRate;
		u16 blockAlign;
		u16 bitsPerSample;
	};

	// Wave data header.
	struct WaveDataHeader
	{
		static const u32 ChunkID = XERN_FOURCC('d', 'a', 't', 'a');

		u32 subchunkId;
		u32 subchunkSize;
	};

	class WavLoader: public IResourceLoader
	{
	public:
		WavLoader();
		~WavLoader();

		virtual bool CanLoadResource(const std::string &filename, const std::string &group) const;
		virtual bool CanLoadResource(const std::string &mime) const;

		virtual boost::shared_ptr<IResource>
		LoadResource(const std::string &filename, const std::string &group, const std::string &path) const;
		virtual boost::shared_ptr<IResource>
		LoadResource(const std::string &mime, boost::shared_ptr<IDataFilter> data) const;
	};

	static PluginFactory<WavLoader> wavLoaderFactory("ResourceLoader", "WavLoader");

	WavLoader::WavLoader()
	{
	}

	WavLoader::~WavLoader()
	{
	}

	bool WavLoader::CanLoadResource(const std::string &filename, const std::string &group) const
	{
		return FileExtension(filename) == ".wav";
	}

	bool WavLoader::CanLoadResource(const std::string &mime) const
	{
		return mime == "audio/vnd.wave";
	}

	boost::shared_ptr<IResource>
	WavLoader::LoadResource(const std::string &filename, const std::string &group, const std::string &path) const
	{
		// Sanity check.
		assert(CanLoadResource(filename, group));

		// Open the file.
		FILE *file = fopen(path.c_str(), "rb");
		if(!file)
			throw XernException("Failed to open file.");

		boost::shared_ptr<FileFilter> filter(new FileFilter(file, true));
		return LoadResource("audio/vnd.wave", filter);
	}

	boost::shared_ptr<IResource>
	WavLoader::LoadResource(const std::string &mime, boost::shared_ptr<IDataFilter> filter) const
	{
		assert(CanLoadResource(mime));

		// Create the decoder.
		DataStream in(filter);

		// Read the header.
		WaveHeader header;
		in >> header.chunkId >> header.chunkSize >> header.format;
		if(header.chunkId != WaveHeader::ChunkID ||
			header.format != WaveHeader::Format)
			throw XernException("Invalid wav file.");

		// Read the wave format.
		WaveFormat format;

		// Check the format header.
		in >> format.subchunkId >> format.subchunkSize;
		if(format.subchunkId != WaveFormat::ChunkID ||
		   format.subchunkSize != WaveFormat::ChunkSize)
			throw XernException("Invalid wave format.");

		// Continue reading the format
		in >> format.audioFormat >> format.numChannels;
		in >> format.sampleRate >> format.byteRate;
		in >> format.blockAlign >> format.bitsPerSample;

		// Only PCM wave files are supported.
		if(format.audioFormat != WaveFormat::PcmFormat)
			throw XernException("Unsupported wave audio format.");

		// Read the data header.
		WaveDataHeader dataHeader;
		in >> dataHeader.subchunkId >> dataHeader.subchunkSize;

		// Check for the data signature.
		if(dataHeader.subchunkId != WaveDataHeader::ChunkID)
			throw XernException("Expected wave data chunk.");

		// Create the wave sampler.
		boost::shared_ptr<WavSampler> sampler(new WavSampler());
		sampler->numchannels = format.numChannels;
		sampler->sampleSize = format.bitsPerSample/8;
		sampler->sampleRate = format.sampleRate;
		sampler->numsamples = dataHeader.subchunkSize /(sampler->sampleSize);

		// Read the samples
		sampler->dataSize = dataHeader.subchunkSize;
		sampler->data = new u8[dataHeader.subchunkSize];
		in.Read(dataHeader.subchunkSize, sampler->data);

		// Return the sampler.
		return sampler;
	}

}; // namespace XernWav
